package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	http.HandleFunc("/healthz", healthz)
	http.HandleFunc("/hello", hello)
	http.HandleFunc("/", response)

	go func() {
		err := http.ListenAndServe(":8000", nil)
		if err != nil {
			log.Fatal(err)
		}
	}()

	s := <-quit
	fmt.Println("exit...", s)
	Exit()
}

func healthz(w http.ResponseWriter, r *http.Request) {
	// io.WriteString(w, "ok")
	w.Write([]byte("ok"))
}

func hello(w http.ResponseWriter, r *http.Request) {
	// io.WriteString(w, "ok")
	w.WriteHeader(501)
	w.Write([]byte("not implemented"))
}

func response(w http.ResponseWriter, r *http.Request) {
	//get VERSION variable
	ver := os.Getenv("VERSION")
	h := r.Header
	h.Add("VERSION", ver)
	//write to response header
	for key, values := range h {
		for _, v := range values {
			w.Header().Add(key, v)
		}
	}

	fmt.Println("response header :", h)

	//log
	fmt.Printf("visit from ip: %v status code: %d", r.Host, 200)

	fmt.Fprintln(w, h)
}

func Exit() {
	fmt.Println("清理资源，准备退出...")
	os.Exit(0)
}
